// src/store/index.js
import { createStore } from 'vuex';

export default createStore({
  state: {
    isAuthenticated: false,
    menuItems: [],
  },
  mutations: {
    setAuthenticated(state, value) {
      state.isAuthenticated = value;
    },
    setMenuItems(state, items) {
      console.log('Setting menu items:', items); // 添加日志
      state.menuItems = items;
    },
  },
  actions: {
    initializeStore({ commit }) {
      const user = JSON.parse(localStorage.getItem('user'));
      if (user) {
        console.log('Initializing store with user:', user); // 添加日志
        commit('setAuthenticated', true);
        commit('setMenuItems', user.resourcesTree);
      }
    },
    loginSuccess({ commit }, payload) {
      console.log('Login success, payload:', payload); // 添加日志
      commit('setAuthenticated', true);
      commit('setMenuItems', payload.resourcesTree);
      localStorage.setItem('user', JSON.stringify(payload));
      localStorage.setItem('staffInfo', JSON.stringify(payload.staff));
      localStorage.setItem('token', JSON.stringify(payload.token));
    },
    logout({ commit }) {
      commit('setAuthenticated', false);
      commit('setMenuItems', []);
      localStorage.removeItem('user');
      localStorage.removeItem('staffInfo');
      localStorage.removeItem('token');
    },
  },
});